package com.itclass.auth.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itclass.auth.enums.AccountTypeEnum;
import com.itclass.auth.mapper.SysRoleMapper;
import com.itclass.auth.mapper.SysUserMapper;
import com.itclass.auth.mapper.SysUserRoleMapper;
import com.itclass.auth.pojo.db.SysRole;
import com.itclass.auth.pojo.db.SysUser;
import com.itclass.auth.pojo.db.SysUserRole;
import com.itclass.auth.pojo.dto.GithubUser;
import com.itclass.auth.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.beans.Transient;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Override
    public SysUser queryUserByUsername(String username) {
        return sysUserRoleMapper.queryUserByUsername(username);
    }

    @Transactional
    @Override
    public SysUser saveGithubUser(GithubUser githubUser) {

        SysUser user = sysUserRoleMapper.queryUserByOpenId(githubUser.getId().toString());
        // 不等于 null 证明数据库已经有了，不用注册了
        if (null != user) {
            return user;
        }

        // 数据库没有这个用户信息，注册用户信息，并默认给   EDITOR 角色权限

        Date currentDate = new Date();
        SysUser sysUser = new SysUser();
        sysUser.setOpenId(githubUser.getId().toString());
        sysUser.setName(githubUser.getName());

        sysUser.setUsername(githubUser.getLogin());
        sysUser.setStatus(1);
        sysUser.setIsDeleted(1);
        sysUser.setType(AccountTypeEnum.GITHUB.getType());
        sysUser.setCreateTime(currentDate);
        // 保存用户
        boolean save = this.save(sysUser);

        if (save) {
            // 查询这个角色的id
            SysUserRole sysUserRole = new SysUserRole();
            QueryWrapper<SysRole> queryRoleWrapper = new QueryWrapper<>();
            queryRoleWrapper.eq("role_code", "EDITOR");
            SysRole sysRole = sysRoleMapper.selectOne(queryRoleWrapper);
            sysUser.setRoleList(Arrays.asList(sysRole));

            // 新增用户角色关系
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(sysRole.getId());
            sysUserRole.setCreateTime(currentDate);
            sysUserRole.setIsDeleted(1);
            return sysUserRoleMapper.insert(sysUserRole) > 0 ? sysUser : null;


        }
        return null;
    }

    @Transactional
    @Override
    public void saveLdapUser(UserDetails userDetails, DirContextOperations userData) {
        SysUser user = sysUserRoleMapper.queryUserByUsername(userDetails.getUsername());
        // 不等于 null 证明数据库已经有了，不用注册了
        if (null != user) {
            return;
        }

        // 数据库没有这个用户信息，注册用户信息

        Date currentDate = new Date();
        SysUser sysUser = new SysUser();

        sysUser.setName(userDetails.getUsername());
        sysUser.setOpenId(userData.getDn().toString());
        sysUser.setUsername(userDetails.getUsername());
        sysUser.setPassword(userDetails.getPassword());
        sysUser.setStatus(1);
        sysUser.setIsDeleted(1);
        sysUser.setType(AccountTypeEnum.LDAP.getType());
        sysUser.setCreateTime(currentDate);
        // 保存用户
        boolean save = this.save(sysUser);

        if (save) {
            List<? extends GrantedAuthority> authorities = (List<? extends GrantedAuthority>) userDetails.getAuthorities();

            List<SysRole> sysRoles = null;
            // 判断权限角色是否不为null
            if (!CollectionUtils.isEmpty(authorities)) {
                String[] roleArr = new String[authorities.size()];
                for (int i = 0; i < authorities.size(); i++) {
                    GrantedAuthority authority = authorities.get(i);
                    String role = authority.getAuthority().substring(5, authority.getAuthority().toString().length());
                    roleArr[i] = role;
                }

                // 查询这个角色的id

                QueryWrapper<SysRole> queryRoleWrapper = new QueryWrapper<>();
                queryRoleWrapper.in("role_code", roleArr);
                queryRoleWrapper.eq("is_deleted","1");
                sysRoles = sysRoleMapper.selectList(queryRoleWrapper);
            }

            if (!CollectionUtils.isEmpty(sysRoles)) {
                SysUserRole sysUserRole = new SysUserRole();
                // 新增用户角色关系
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setCreateTime(currentDate);
                sysUserRole.setIsDeleted(1);
                for (SysRole sysRole : sysRoles) {
                    sysUserRole.setRoleId(sysRole.getId());
                    // 插入用户角色关系
                    sysUserRoleMapper.insert(sysUserRole);
                }
            }
        }
    }
}